#!/usr/bin/env python3

'''
调用gender_prediction接口
'''
from gender import *
from icrawler.builtin import GoogleImageCrawler
import os,sys
import shutil

class gender_prediction(object):
    def __init__(self,name,org,follow,i):
        self.name = name
        self.org = org
        self.follow = follow
        self.i = i

    def use_gender_prediction(self):
        g = Gender()
        self.get_image_url()

        #print(g.predict(name='Jie Tang', org='Tsinghua University', image_url='http://www.cs.tsinghua.edu.cn/publish/cs/4616/20110330101939787483549/20190321114128398502759.jpg'))
        #返回根据genderprediction结果

        if os.path.exists('../image/'+ str(self.follow) + '/' + str(self.i) +'/000001.png'):
            image_file = '../image/'+ str(self.follow) + '/' + str(self.i) +'/000001.png'
        elif os.path.exists('../image/'+ str(self.follow) + '/' + str(self.i) +'/000001.jpg'):
            image_file = '../image/'+ str(self.follow) + '/' + str(self.i) +'/000001.jpg'
        else:
            image_file = '../image/0.jpg'

        #print(g.predict(name=self.name,org=self.org,image_file=image_file))

        gender_prediction_result = g.predict(name=self.name,org=self.org,image_file=image_file)

        #删除文件夹操作
        #shutil.rmtree("../image/" + str(self.i))

        return gender_prediction_result

    '''
        判断照片是jpg还是png
    '''
    @staticmethod
    def judge_jpg_png():
        if os.path.exists('../image/000001.png'):
            return '../image/000001.png'
        elif os.path.exists('../image/000001.jpg'):
            image_file = '../image/000001.jpg'
            return '../image/000001.jpg'
        else:
            #如果下载下来的图片不是jpg也不是png格式的话，则返回第二张照片
            return '../image/000002.jpg'

    '''
        这里用谷歌图像然后利用name和org返回第一张图片的地址
    '''
    def get_image_url(self):
        #存储照片路径
        os.mkdir("../image/" + str(self.follow) + '/' + str(self.i))
        google_storage = {'root_dir': '/gratulate/paper/program/data_mining/image/' + str(self.follow) + '/' + str(self.i)}

        google_crawler = GoogleImageCrawler(parser_threads=1,
                                           downloader_threads=1,
                                           storage=google_storage)
        google_crawler.crawl(keyword=self.name + " " + self.org,max_num=1)
